﻿using System;
using System.IO;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Xml.Serialization;
using PumpStationClient.PumpService;

namespace PumpStationClient
{
    class Program
    {
        private const string VERSION = "1.0";

        static void Main(string[] args)
        {
            var program = new Program();

            // Start a new thread to handle console input
            new Thread(() =>
            {
                while (true)
                {
                    string line = Console.ReadLine();
                    if (line == "exit")
                    {
                        Console.Write("Are you sure you want to exit? [y/n]: ");
                        if (Console.ReadLine() == "y")
                        {
                            program.Stop();
                            break;
                        }
                    }
                }
            }).Start();
        }

        private readonly PumpStation _pumpStation;
        private readonly Simulator _simulator;

        public Program()
        {
            // Read configuration
            var stream = new StreamReader(@"config.xml", Encoding.UTF8);
            var config = (Configuration)new XmlSerializer(typeof(Configuration)).Deserialize(stream);

            // Setup WCF Service
            var callback = new PumpStationCallback();
            var instanceContext = new InstanceContext(callback);
            var proxy = new PumpStationServiceClient(instanceContext);

            // Initialize main object
            _pumpStation = new PumpStation("123.456.789.1", 9000, proxy);

            var pumps = new Pump[config.Pumps.Length];
            for (var i = 0; i < config.Pumps.Length; i++)
            {
                pumps[i] = new Pump(config.Pumps[i].Capacity);
                //pumps[i].StatusChanged += OnPumpStatusChanged;
            }
            //_pumpStation.Pumps = config.Pumps.Select(pump => new Pump(pump.Capacity)).ToArray();
            _pumpStation.Pumps = pumps;

            callback.Station = _pumpStation;

            // Register with the WCF Service
            _pumpStation.Register();

            _simulator = new Simulator(_pumpStation);
            _simulator.Start();
        }

        private void Stop()
        {
            _simulator.Stop();
            _simulator.Join();
        }

        /*private void OnPumpStatusChanged(Pump pump)
        {
            for (var i = 0; i < _pumpStation.Pumps.Length; i++)
            {
                if (_pumpStation.Pumps[i] == pump)
                {
                    _pumpStation.Proxy.SetPumpRunning(_pumpStation.Id, i, pump.Running);
                }
            }
        }*/
    }
}
